package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.SetmealDao;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    /**
     * 新增套餐
     * @param checkgroupIds
     * @param setmeal
     */
    @Override
    public void addSetmeal(List<Integer> checkgroupIds, Setmeal setmeal) {
        //新增套餐
        setmealDao.addSetmeal(setmeal);
        //新增套餐与检查组的关联关系
        if (checkgroupIds != null && !checkgroupIds.isEmpty()){
            setmealDao.addSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
        }else {
            throw new RuntimeException("检查组不能为空");
        }

    }

    /**
     * 编辑套餐
     * @param checkgroupIds
     * @param setmeal
     */
    @Override
    @Transactional
    public void editSetmealAndCheckGroup(List<Integer> checkgroupIds, Setmeal setmeal) {
        //编辑套餐基本属性
        setmealDao.editSetmeal(setmeal);

        //删除套餐与检查组的关联关系
        setmealDao.deleteSetmealAndCheckGroup(setmeal.getId());
        //新增套餐与检查组的关联关系
        if (checkgroupIds != null && !checkgroupIds.isEmpty()){
            setmealDao.addSetmealAndCheckGroup(setmeal.getId(),checkgroupIds);
        }
    }

    /**
     * 根据套餐id查询套餐
     *
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealDao.findById(id);
        return setmeal;
    }

    /**
     * 分页查询套餐
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        List<Setmeal> setmeals = setmealDao.findPage(queryPageBean.getQueryString());
        PageInfo<Setmeal> pageInfo = new PageInfo<>(setmeals);
        PageResult pageResult = new PageResult(pageInfo.getTotal(),pageInfo.getList());
        return pageResult;
    }

    /**
     * 查询所有套餐信息
     * @return
     */
    @Override
    public List<Setmeal> getSetmeal() {
        List<Setmeal> setmeals = setmealDao.getSetmeal();
        return setmeals;
    }

    /**
     * 根据套餐id查询套餐和检查组
     * @param id
     * @return
     */
    @Override
    public Setmeal findSetmealAndGroupById(Integer id) {
        Setmeal setmeal = setmealDao.findSetmealAndGroupById(id);
        return setmeal;
    }
}
